package agency.sales;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import agency.Sales;
import common.Card;
import common.Product;
import dict.AgencyDict;
import dict.BcDict;
import entities.TBank;
import entities.TBc;
import entities.TCard;
import entities.TTransaction;
import net.sf.json.JSONObject;
import util.HttpUtil;
import util.LogUtil;
import utils.AesUtil;
import utils.DateUtil;
import utils.DigestUtil;
import utils.NumberUtil;
import utils.StringUtil;

public class Wonedc implements Sales {
          
	private static String PATH = "https://www.woonpay.com/Interface/";
	private static String version = "1.0.0";
	private static String encoding = "utf-8";
	private static String language = "en-us";
	private static String currency = "CNY";
	private static String transtype = "2";
	private static String callbackurl = "https://gateway.atepay.com/Receive";
	private static String browserbackurl = "https://gateway.atepay.com/Receive";
	private static String shippingfee = "0.00";

	private static String remark2 = "remark 2 stand by ";
	private static String remark3 = "remark 3 stand by ";

	@SuppressWarnings("unchecked")
	public void process(TBc bc, TTransaction transaction, TBank bank, TCard card) {

		Map<String, String> requestMap = new TreeMap<String, String>();
		Map<String, String> responseMap = new TreeMap<String, String>();
		String res = null;
		// 消费

		requestMap.put("version", version);
		requestMap.put("encoding", encoding);
		requestMap.put("language", language);
		requestMap.put("merchantid", bank.getBnkMer());
		requestMap.put("orderid", bc.getBcNo());
		requestMap.put("orderdate", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
		requestMap.put("currency", currency);
		requestMap.put("orderamount", NumberUtil.transfer(bc.getBcAmount()));
		requestMap.put("transtype", transtype);
		requestMap.put("callbackurl", callbackurl);
		requestMap.put("browserbackurl", browserbackurl);
		requestMap.put("accessurl", transaction.getTxnSite().replaceAll("http://", "").replaceAll("https://", ""));
		requestMap.put("remark1", card.getCrdIp());
		requestMap.put("remark2", remark2);
		requestMap.put("remark3", remark3);

		if (Card.isVisa(card.getCrdNumber())) {
			requestMap.put("cardtype", "1");
		}
		if (Card.isMaster(card.getCrdNumber())) {
			requestMap.put("cardtype", "2");
		}
		if (Card.isJcb(card.getCrdNumber())) {
			requestMap.put("cardtype", "3");
		}

		try {
			String number = card.getCrdNumber();
			String expire = AesUtil.AES_Decrypt(AesUtil.KEY, card.getCrdExpire());
			String cvv = AesUtil.AES_Decrypt(AesUtil.KEY, card.getCrdCvv());
			requestMap.put("cardnum", number);
			requestMap.put("expdate", "20" + expire.substring(2, 4) + expire.substring(0, 2));
			requestMap.put("cvv", cvv);
		} catch (Exception e) {
			bc.setBcMark("555");
			bc.setBcInfo("edc sale data encrpt exception");
			bc.setBcCode(AgencyDict.WON_ENCRYPT_EXCEPTION);
			bc.setBcMessage(AgencyDict.AGENCY.get(AgencyDict.WON_ENCRYPT_EXCEPTION));
			return;
		}

		if (StringUtil.isEmpty(transaction.getTxnProduct())) {
			requestMap.put("productname1", Product.fetchPctName());
			requestMap.put("productname2", Product.fetchPctName());
			requestMap.put("productname3", Product.fetchPctName());
		} else {
			requestMap.put("productname1", transaction.getTxnProduct());
			requestMap.put("productname2", transaction.getTxnProduct());
			requestMap.put("productname3", transaction.getTxnProduct());
		}
		requestMap.put("productsn1", Product.fetchPctSn());
		requestMap.put("productsn2", Product.fetchPctSn());
		requestMap.put("productsn3", Product.fetchPctSn());
		requestMap.put("quantity1", Product.fetchPctQuantity());
		requestMap.put("quantity2", Product.fetchPctQuantity());
		requestMap.put("quantity3", Product.fetchPctQuantity());
		requestMap.put("unit1", Product.fetchPctUnit());
		requestMap.put("unit2", Product.fetchPctUnit());
		requestMap.put("unit3", Product.fetchPctUnit());
		requestMap.put("shippingfee", shippingfee);

		requestMap.put("billfirstname", card.getCrdHfname());
		requestMap.put("billlastname", card.getCrdHlname());
		requestMap.put("billcountry", card.getCrdHcountry());
		requestMap.put("billprovince", card.getCrdHstate());
		requestMap.put("billcity", card.getCrdHcity());
		requestMap.put("billaddress", card.getCrdHaddr());
		requestMap.put("billemail", card.getCrdHemail());
		requestMap.put("billpost", card.getCrdHzip());
		requestMap.put("billphone", card.getCrdHphone());

		requestMap.put("deliveryfirstname", card.getCrdCfname());
		requestMap.put("deliverylastname", card.getCrdClname());
		requestMap.put("deliverycountry", card.getCrdCcountry());
		requestMap.put("deliveryprovince", card.getCrdCstate());
		requestMap.put("deliverycity", card.getCrdCcity());
		requestMap.put("deliveryaddress", card.getCrdCaddr());
		requestMap.put("deliveryemail", card.getCrdCemail());
		requestMap.put("deliverypost", card.getCrdCzip());
		requestMap.put("deliveryphone", card.getCrdCphone());

		requestMap.put("merchantcert", bank.getBnkKey());

		String str = requestMap.get("merchantcert").toString() + "|" + requestMap.get("merchantid").toString() + "|" + requestMap.get("orderdate").toString() + "|" + requestMap.get("orderid").toString() + "|"
				+ requestMap.get("orderamount").toString();
		requestMap.put("signature", DigestUtil.md5(str));

		// 日志打印发送数据
		StringBuffer send = new StringBuffer();
		for (Map.Entry<String, String> e : requestMap.entrySet()) {
			send.append(e.getKey() + "=" + e.getValue() + "&");
		}
		LogUtil.agency("WONEDC_SALES", send.toString());

		try {
			res = new HttpUtil().ssl(PATH, requestMap);
		} catch (Exception e) {
			bc.setBcMark("555");
			bc.setBcInfo("edc sale data encrpt exception");
			bc.setBcCode(AgencyDict.WON_TRANSMISSION_EXCEPTION);
			bc.setBcMessage(AgencyDict.AGENCY.get(AgencyDict.WON_TRANSMISSION_EXCEPTION));
			return;
		}

		if (StringUtil.isEmpty(res)) {
			bc.setBcMark("555");
			bc.setBcInfo("edc sale data response exception");
			bc.setBcCode(AgencyDict.WON_TRANSMISSION_EXCEPTION);
			bc.setBcMessage(AgencyDict.AGENCY.get(AgencyDict.WON_TRANSMISSION_EXCEPTION));
			return;
		}

		if (res.indexOf("502 Bad Gateway") >= 0) {
			try {
				Thread.sleep(3000);
				res = new HttpUtil().ssl(PATH, requestMap);
			} catch (Exception e) {
				bc.setBcMark("555");
				bc.setBcInfo("edc sale data encrpt exception");
				bc.setBcCode(AgencyDict.WON_TRANSMISSION_EXCEPTION);
				bc.setBcMessage(AgencyDict.AGENCY.get(AgencyDict.WON_TRANSMISSION_EXCEPTION));
				return;
			}
		}

		try {
			responseMap = JSONObject.fromObject(res);
		} catch (Exception e) {
			bc.setBcMark("555");
			bc.setBcInfo("edc sale data disembly exception");
			bc.setBcCode(AgencyDict.WON_TRANSMISSION_EXCEPTION);
			bc.setBcMessage(AgencyDict.AGENCY.get(AgencyDict.WON_TRANSMISSION_EXCEPTION));
			return;
		}

		LogUtil.agency("WONEDC_SALES", responseMap.toString());

		if (!responseMap.containsKey("responseData_code")) {
			bc.setBcMark("555");
			bc.setBcInfo("edc sale data parameter exception");
			bc.setBcCode(AgencyDict.WON_TRANSMISSION_EXCEPTION);
			bc.setBcMessage(AgencyDict.AGENCY.get(AgencyDict.WON_TRANSMISSION_EXCEPTION));
			return;
		}

		if (!responseMap.containsKey("responseData_msg")) {
			bc.setBcMark("555");
			bc.setBcInfo("edc sale data parameter exception");
			bc.setBcCode(AgencyDict.WON_TRANSMISSION_EXCEPTION);
			bc.setBcMessage(AgencyDict.AGENCY.get(AgencyDict.WON_TRANSMISSION_EXCEPTION));
			return;
		}

		if (!responseMap.get("responseData_code").equals("0000")) {
			bc.setBcMark(responseMap.get("responseData_code"));
			bc.setBcInfo(responseMap.get("responseData_msg"));
			bc.setBcCode(AgencyDict.WON_SALES_FAILURE);
			bc.setBcMessage(AgencyDict.AGENCY.get(AgencyDict.WON_SALES_FAILURE));
			return;
		}

		bc.setBcState("1");
		bc.setBcRef(bc.getBcNo());
		bc.setBcCard(card.getCrdFake());
		bc.setBcTime(DateUtil.format(new Date(), DateUtil.DATE));
		bc.setBcMark(responseMap.get("responseData_code"));
		bc.setBcInfo(responseMap.get("responseData_msg"));
		bc.setBcCode(BcDict.BC_SUCCESS);
		bc.setBcMessage(BcDict.MESSAGES.get(BcDict.BC_SUCCESS));
		return;
	}

}